package cn.ges.js

import cn.ges.bean.BeanUtil
import cn.ges.type.BlankHelper
import java.lang.reflect.Field
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author gespent@163.com
 * @date 2020/05/18 16:18
 */
class JsHelper {
    companion object {

        fun getIdField(clazz: Class<*>): Field? {
            return try {
                clazz.getDeclaredField("id")
            } catch (e: NoSuchFieldException) {
                null
            }
        }

        fun getLongField(clazz: Class<*>): ArrayList<Field>? {
            val arrayList = ArrayList<Field>()
            val declaredFields = clazz.declaredFields
            declaredFields.forEach {
                if (it.type == Long::class.java || it.type.name == "java.lang.Long") {
                    arrayList.add(it)
                }

            }
            return arrayList
        }

        fun getFields(clazz: Class<*>, vararg fieldNames: String?): ArrayList<Field>? {
            val fields = ArrayList<Field>(fieldNames.size)

            try {
                for (fieldName in fieldNames) {
                    fields.add(clazz.getDeclaredField(fieldName))
                }
            } catch (e: NoSuchFieldException) {
                return null
            }
            return fields
        }

        fun castBeanField2String(obj: Any?, field: ArrayList<Field>, unless: ArrayList<Field>?): HashMap<Any, Any> {
            val objectObjectHashMap: HashMap<Any, Any> = BeanUtil.bean2Map(obj)
            for (result in field) {
                val name = result.name
                val o = objectObjectHashMap[name]
                if (o != null) {
                    objectObjectHashMap[name] = o.toString()
                }
            }
            if (unless != null) {
                for (item in unless) {
                    objectObjectHashMap.remove(item.name)
                }
            }
            return objectObjectHashMap
        }

        fun castListField2String(list: ArrayList<*>, field: ArrayList<Field>, unless: ArrayList<Field>?): ArrayList<*>? {
            if (BlankHelper.listIsBlank(list)) {
                return list
            }
            val hashMaps = ArrayList<HashMap<Any, Any>>(list.size)
            list.forEach { item: Any? -> hashMaps.add(castBeanField2String(item, field, unless)) }
            return hashMaps
        }

        fun <T> castListLongField2String(list: ArrayList<T>, clazz: Class<T>): ArrayList<*>? {
            if (BlankHelper.listIsBlank(list)) {
                return list
            }
            val hashMaps = ArrayList<HashMap<Any, Any>>(list.size)
            val longField = getLongField(clazz) ?: return list
            list.forEach { item: Any? -> hashMaps.add(castBeanField2String(item, longField, null)) }
            return hashMaps
        }


    }

}